<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
<?xml-stylesheet type="text/css" href="/tests/SimpleTest/test.css"?>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=664783
-->
<window title="Mozilla Bug 664783"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
  <script type="application/javascript"
          src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
  <script type="application/javascript" src="dom_worker_helper.js"/>

  <!-- test results are displayed in the html:body -->
  <body xmlns="http://www.w3.org/1999/xhtml">
  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=664783"
     target="_blank">Mozilla Bug 664783</a>

  <div id="content" style="display: none">
    <input id="fileList" type="file"></input>
  </div>

  </body>

  <!-- test code goes here -->
  <script type="application/javascript">
  <![CDATA[

  /** Test for Bug 664783 **/

  var fileNum = 0;

  /**
   * Create a file which contains the given data and optionally adds the specified file extension.
   */
  function createFileWithData(fileData, /** optional */ extension) {
    var testFile = Components.classes["@mozilla.org/file/directory_service;1"]
                       .getService(Components.interfaces.nsIProperties)
                       .get("ProfD", Components.interfaces.nsIFile);
    var fileExtension = (extension == undefined) ? "" : "." + extension;
    testFile.append("workerFileReaderSync" + fileNum++ + fileExtension);

    var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                        .createInstance(Components.interfaces.nsIFileOutputStream);
    outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
                   0666, 0);
    outStream.write(fileData, fileData.length);
    outStream.close();

    var fileList = document.getElementById('fileList');
    fileList.value = testFile.path;

    return fileList.files[0];
  }

  function convertToUTF16(s) {
    res = "";
    for (var i = 0; i < s.length; ++i) {
      c = s.charCodeAt(i);
      res += String.fromCharCode(c & 255, c >>> 8);
    }
    return res;
  }

  /**
   * Converts the given string to a data URL of the specified mime type.
   */
  function convertToDataURL(mime, s) {
    return "data:" + mime + ";base64," + btoa(s);
  }

  /**
   * Create a worker to read a file containing fileData using FileReaderSync and
   * checks the return type against the expected type. Optionally set an encoding
   * for reading the file as text.
   */
  function readFileData(fileData, expectedText, /** optional */ encoding) {
    var worker = new Worker("fileReaderSync_worker.js");

    worker.onmessage = function(event) {
      is(event.data.text, expectedText, "readAsText in worker returned incorrect result.");
      is(event.data.bin, fileData, "readAsBinaryString in worker returned incorrect result.");
      is(event.data.url, convertToDataURL("application/octet-stream", fileData), "readAsDataURL in worker returned incorrect result.");
      is(event.data.arrayBuffer.byteLength, fileData.length, "readAsArrayBuffer returned buffer of incorrect length.");
      finish();
    };

    worker.onerror = function(event) {
      ok(false, "Worker had an error: " + event.message);
      finish();
    };

    var params = {file: createFileWithData(fileData), encoding: encoding};

    worker.postMessage(params);

    waitForWorkerFinish();
  }

  /**
   * Create a worker which reuses a FileReaderSync to read multiple files as DataURLs.
   */
  function reuseReaderForURL(files, expected) {
    var worker = new Worker("fileReaderSync_worker.js");

    worker.onerror = function(event) {
      ok(false, "Worker had an error: " + event.message);
      finish();
    };

    var k = 0;
    worker.onmessage = function(event) {
      is(event.data.url, expected[k], "readAsDataURL in worker returned incorrect result when reusing FileReaderSync.");
      k++;
      finish();
    };

    for (var i = 0; i < files.length; ++i) {
      var params = {file: files[i], encoding: undefined};
      worker.postMessage(params);
      waitForWorkerFinish();
    }
  }

  /**
   * Create a worker which reuses a FileReaderSync to read multiple files as text.
   */
  function reuseReaderForText(fileData, expected) {
    var worker = new Worker("fileReaderSync_worker.js");

    worker.onerror = function(event) {
      ok(false, "Worker had an error: " + event.message);
      finish();
    };

    var k = 0;
    worker.onmessage = function(event) {
      is(event.data.text, expected[k++], "readAsText in worker returned incorrect result when reusing FileReaderSync.");
      finish();
    };

    for (var i = 0; i < fileData.length; ++i) {
      var params = {file: createFileWithData(fileData[i]), encoding: undefined};
      worker.postMessage(params);
      waitForWorkerFinish();
    }
  }


  /**
   * Creates a a worker which reads a file containing fileData as an ArrayBuffer.
   * Verifies that the ArrayBuffer when interpreted as a string matches the original data.
   */
  function readArrayBuffer(fileData) {
    var worker = new Worker("fileReaderSync_worker.js");

    worker.onmessage = function(event) {
      var view = new Uint8Array(event.data.arrayBuffer);
      is(event.data.arrayBuffer.byteLength, fileData.length, "readAsArrayBuffer returned buffer of incorrect length.");
      is(String.fromCharCode.apply(String, view), fileData, "readAsArrayBuffer returned buffer containing incorrect data.");
      finish();
    };

    worker.onerror = function(event) {
      ok(false, "Worker had an error: " + event.message);
      finish();
    };

    var params = {file: createFileWithData(fileData), encoding: undefined};

    worker.postMessage(params);

    waitForWorkerFinish();
  }

  // Empty file.
  readFileData("", "");

  // Typical use case.
  readFileData("text", "text");

  // Test reading UTF-16 characters.
  readFileData(convertToUTF16("text"), "text", "UTF-16");

  // First read a file of type "text/plain", then read a file of type "application/octet-stream".
  reuseReaderForURL([createFileWithData("text", "txt"), createFileWithData("text")],
                    [convertToDataURL("text/plain", "text"),
                     convertToDataURL("application/octet-stream", "text")]);

  // First read UTF-16 characters marked using BOM, then read UTF-8 characters.
  reuseReaderForText([convertToUTF16("\ufefftext"), "text"],
                     ["text", "text"]);

  // Reading data as ArrayBuffer.
  readArrayBuffer("");
  readArrayBuffer("text");

  ]]>
  </script>
</window>
